import json


def str_to(val: str):
    if 'true' == val:
        return True
    elif 'false' == val:
        return False

    condition, value = _convert_type(int, val)
    if condition:
        return value

    condition, value = _convert_type(float, val)
    if condition:
        return value

    condition, value = _convert_type(json.loads, val)
    if condition:
        return value

    return val


def to_str(val):
    if isinstance(val, bool):
        if val:
            return "true"
        return "false"
    if isinstance(val, (tuple, list, set, dict)):
        return json.dumps(val, ensure_ascii=False)

    return str(val)


def _convert_type(type_fun, val: str):
    try:
        val = type_fun(val)
        return True, val
    except ValueError:
        return False, None
